package com.lyy.lottery.service.impl;

import com.lyy.lottery.common.errorcode.ServiceErrorCodeConstants;
import com.lyy.lottery.common.exception.ServiceException;
import com.lyy.lottery.common.util.*;
import com.lyy.lottery.service.VerificationCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

//    @Autowired
//    private SMSUtil smsUtil;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 对于redis中的key进行标准化：为区分业务给key定义前缀
     * VerificationCode_13377525754：1234、User_13377525754：userInfo 避免值的覆盖
     */

    private static final String VERIFICATION_CODE_PREFIX="Verification_Code";
    private static final Long VERIFICATION_CODE_TIMEOUT=60L;

    //private static final String VERIFICATION_CODE_TIMEPLATE_CODE="SMS_154950909";

    @Override
    public void sendVerificationCode(String phoneNumber) {
        //1、校验手机号
        if (!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        //2、生成随机验证码
        String code= CaptchaUtil.getCaptcha(4);
        //3、发送验证码
        //templateParam："{\"code\":\"1234\"}"
        /*Map<String,String> map=new HashMap<>();
        map.put("code",code);
        smsUtil.sendMessage(VERIFICATION_CODE_TIMEPLATE_CODE,
                phoneNumber,
                JacksonUtil.writeValueAsString(map));*/
        log.info("短信验证码发送成功！");
        //4、缓存验证码
        redisUtil.set(VERIFICATION_CODE_PREFIX+phoneNumber,code,VERIFICATION_CODE_TIMEOUT);
    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        //1、校验手机号
        if (!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        //2、获取验证码
        return redisUtil.get(VERIFICATION_CODE_PREFIX+phoneNumber);
    }
}
